import { UserData } from "./UserData";

interface Point {
    x: number;
    y: number;
}
interface _creatSprite {
    img: string;
    x?: number;
    y?: number;
    width?: number;
    height?: number;
    align?: string;
}
export default class Util {
    public static APIURL: string;
    public static GameName: string;
    /**
     * 初始化perfab变量
    */
    public static initPerfabs(ui: any): void {
        ui['_children'] && ui['_children'].forEach(element => {
            if (element['var']) {
                ui[element['var']] = element;
            }
        });
    }



    /**
     * 给定一个速度和方向，分解成X轴和Y轴方向分别的速度
     * @param { Number } velocity
     * @anle { Number } angle: in radians.
     */
    public static velocityDecomposition(velocity: number, radian: number): Point {
        let cos = Math.cos(radian);
        let sin = Math.sin(radian);

        return {
            x: cos * velocity,
            // Y轴坐标系与真实世界相反
            y: -sin * velocity
        };
    }

    /**
     * 将角度换算成弧度
     */
    public static convertDegree2Radian(deg: number): number {
        return deg * Math.PI / 180;
    }

    /**
     * 将弧度换算成角度
     */
    public static convertRadian2Degree(radian: number): number {
        return radian * 180 / Math.PI;
    }

    /**
     * 保证num在最大值和最小值中间.
    */
    public static getNumInRange(num: number, min: number, max: number): number {
        if (num < min)
            return min;

        else if (num > max)
            return max;

        return num;
    }


    public static showTip(title = '', duration = 1500) {

    }

    /**
     * 计算两点间的距离
    */
    public static getDistance(point1: Point, point2: Point): number {
        const disX = point1.x - point2.x;
        const disY = point1.y - point2.y;
        return Math.sqrt(disX * disX + disY * disY);
    }

    public static checkCircleCollision(circle1, circle2): boolean {
        let dis = Util.getDistance(circle1.center, circle2.center);
        return !!(dis <= (circle1.radius + circle2.radius));
    }

    public static limitNumInRange(num: number, min: number, max: number): number {
        if (num > max) {
            return num - max;
        } else if (num < min) {
            return num + max;
        } else {
            return num;
        }
    }

    /**
     *  获取 两点夹角 弧度
     * @param point1 点1，参照点.
     * @param point2 点2.
     */
    public static getRadians(point1, point2): number {
        let disX = point2.x - point1.x;
        let disY = point2.z - point1.z;
        return Math.atan2(disY, disX)
    }

    public static getMove(from, to) {
        let dis = to - from;
        if (dis < -180) {
            dis += 360;
        } else if (dis > 180) {
            dis -= 360;
        }

        return dis;
    }


    public static isNotNullOrUndefined(obj): boolean {
        return obj !== null && obj !== undefined;
    }

    /**本机存储是否有效*/
    public static isLocalStorageAvailable(): boolean {
        try {
            localStorage.setItem("test", "test");
            localStorage.removeItem("test");
            return "localStorage" in window && window["localStorage"] !== null;
        } catch (e) {
            return false;
        }
    }
    /**获取一串随机字符串*/
    public static randomStr(len: number): string {
        var str = 'abcdefghigklmnopqrstuvwxyz1234567890';
        var chars = [];
        var slen = str.length;
        for (var i = 0; i < len; i++) {
            chars.push(str.charAt(Math.floor(Math.random() * slen)));
        }
        return chars.join('');
    }

    /**
     * 获取本机设备ID,通过保存到文件里一串随机字符.清理本机数据就失效,会重新生成一个.基本满足小白的唯一ID
    */
    public static getMathineId(): string {
        if (Util.isLocalStorageAvailable()) {
            var uid = localStorage.getItem("uid");
            if (uid) {
                return uid;
            }
            uid = Util.randomStr(32);
            localStorage.setItem('uid', uid);
            return uid;
        }
        return "";
    }

    /**
     * 发送API数据请求
    */
    public static postData(act: string, data: any): Promise<any> {
        let promise = new Promise<any>((resolve, reject) => {
            let req = new Laya.HttpRequest();
            const onComp = function (data) {
                if (data['code'] != 0) {
                    reject(data['msg']);
                }
                resolve(data['data']);
            };
            const onFail = function () {
                console.log("接口请求失败");
                reject();
            };
            req.once(Laya.Event.COMPLETE, req, onComp);
            req.once(Laya.Event.ERROR, req, onFail);
            if (typeof data == 'object') {
                data = JSON.stringify(data);
            }
            req.send(Util.APIURL + act, data, "post", "json", ["Content-Type", "application/json", 'game', Util.GameName, 'uid', UserData.instance.userId]);

        });
        return promise;
    }

    public static log(message: string, ...params: any[]): void {
        console.log(message, params);
    }

    public static createSprite(options: _creatSprite) {
        if (typeof options == 'string') {
            options = { img: options };
        }
        //const { img, x, y,width,height,align } = options;
        var btn = new Laya.Sprite();
        btn.loadImage(options.img, Laya.Handler.create(btn, function () {

            if (options.width) {
                btn.width = options.width;
            }
            if (options.height) {
                btn.height = options.height;
            }

            if (options.align == 'center') {
                btn.pivot(.5 * btn.width, 0.5 * btn.height);
            }
        }));

        btn.x = options.x;
        btn.y = options.y;

        return btn;
    }

}